<template>
  <div class="dashboard">
    <div class="status-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="32" color="#1890ff">
                <Monitor />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ formatUptime(systemStatus.uptime) }}</div>
              <div class="stat-label">系统运行时间</div>
              <div class="stat-extra">
                <div class="stat-extra-row">
                  <span class="extra-label">CPU</span>
                  <span class="extra-value">{{ cpuUsageFormatted }}</span>
                </div>
                <el-progress
                  class="stat-extra-progress"
                  :percentage="cpuUsageValue"
                  :show-text="false"
                  :stroke-width="4"
                  :color="getCpuColor(cpuUsageValue)"
                />
                <div class="stat-extra-row">
                  <span class="extra-label">内存</span>
                  <span class="extra-value">{{ memoryUsageFormatted }}</span>
                </div>
                <el-progress
                  class="stat-extra-progress"
                  :percentage="memoryPercentage"
                  :show-text="false"
                  :stroke-width="4"
                  :color="getMemoryColor(memoryPercentage)"
                />
              </div>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="32" color="#52c41a">
                <Setting />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ systemStatus.devices.online }}/{{ systemStatus.devices.total }}</div>
              <div class="stat-label">在线设备</div>
              <div class="stat-change" :class="deviceStatusClass">
                {{ deviceStatusText }}
              </div>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="32" :color="mqttStatusColor">
                <Connection />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ mqttStatusText }}</div>
              <div class="stat-label">MQTT连接</div>
              <div class="stat-extra">
                <div class="stat-extra-row">
                  <div class="stat-extra-item">
                    <span class="extra-label">成功</span>
                    <span class="extra-value">{{ systemStatus.mqtt.messagesSent }}</span>
                  </div>
                  <div class="stat-extra-item">
                    <span class="extra-label">失败</span>
                    <span class="extra-value extra-danger">{{ systemStatus.mqtt.messagesFailed }}</span>
                  </div>
                </div>
                <div class="stat-extra-row">
                  <span class="extra-success" :class="getSuccessRateClass(mqttSuccessRate)">
                    成功率 {{ mqttSuccessRate.toFixed(1) }}%
                  </span>
                </div>
              </div>
              <div class="stat-footnote" v-if="systemStatus.mqtt.lastPublish">
                最后发送 {{ formatTime(systemStatus.mqtt.lastPublish) }}
              </div>
            </div>
          </div>
        </el-col>
        
        <el-col :xs="24" :sm="12" :md="6">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon :size="32" color="#722ed1">
                <DataAnalysis />
              </el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ systemStatus.dataCollection.totalPoints }}</div>
              <div class="stat-label">采集数据点</div>
              <div class="stat-change" :class="getSuccessRateClass(systemStatus.dataCollection.successRate)">
                成功率 {{ systemStatus.dataCollection.successRate.toFixed(1) }}%
              </div>
              <div class="stat-progress">
                <el-progress 
                  :percentage="systemStatus.dataCollection.successRate" 
                  :show-text="false" 
                  :stroke-width="4"
                  :color="getSuccessRateColor(systemStatus.dataCollection.successRate)"
                />
              </div>
              <div class="stat-footnote" v-if="systemStatus.dataCollection.lastCollection">
                最后采集 {{ formatTime(systemStatus.dataCollection.lastCollection) }}
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 实时数据点位 -->
    <el-row :gutter="20" class="mt-4">
      <el-col :span="24">
        <el-card class="status-card data-table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon><DataBoard /></el-icon>
              <span>实时采集点位</span>
              <div class="header-actions">
                <el-tag size="large" type="info">共 {{ dataPointRows.length }} 个点位</el-tag>
              </div>
            </div>
          </template>
          <el-table
            class="data-points-table"
            :data="dataPointRows"
            stripe
            :border="false"
            highlight-current-row
            empty-text="暂无采集数据"
            height="420"
          >
            <el-table-column type="index" label="#" width="60" />
            <el-table-column prop="deviceId" label="设备" min-width="160" show-overflow-tooltip />
            <el-table-column label="类别" width="120">
              <template #default="{ row }">
                <el-tag :type="categoryTagType(row.category)" class="category-tag" effect="plain">
                  {{ row.category }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="key" label="点位名称" min-width="200" show-overflow-tooltip />
            <el-table-column label="实时值" min-width="160">
              <template #default="{ row }">
                <span class="value-highlight">{{ formatPointValue(row.value, row.unit) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="采集时间" min-width="200">
              <template #default="{ row }">
                <div class="timestamp-cell">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatTime(row.timestamp) }}</span>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- WebSocket连接状态 -->
    <div class="websocket-status">
      <el-alert
        v-if="!connected"
        title="实时连接断开"
        type="warning"
        description="与服务器的实时连接已断开，正在尝试重新连接..."
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted } from 'vue'
import {
  Monitor, Setting, Connection, DataAnalysis, DataBoard, Clock
} from '@element-plus/icons-vue'
import { useSystemStatus } from '@/composables/useSystemStatus'
import { systemAPI } from '@/utils/api'

// 系统状态管理
const { 
  systemStatus, 
  connected, 
  connectWebSocket, 
  disconnectWebSocket, 
  formatUptime, 
  formatMemory,
  formatTime
} = useSystemStatus()

// 计算属性
const deviceStatusClass = computed(() => {
  const total = systemStatus.devices.total
  const online = systemStatus.devices.online
  if (total === 0) return 'text-secondary'
  const rate = online / total
  return rate > 0.8 ? 'positive' : rate > 0.5 ? 'text-warning' : 'negative'
})

const deviceStatusText = computed(() => {
  const total = systemStatus.devices.total
  const online = systemStatus.devices.online
  if (total === 0) return '无设备'
  const rate = ((online / total) * 100).toFixed(0)
  return `${rate}% 在线`
})

const cpuUsageValue = computed(() => Number(systemStatus.cpu?.usage ?? 0))
const cpuUsageFormatted = computed(() => `${cpuUsageValue.value.toFixed(1)}%`)
const memoryUsageFormatted = computed(() => {
  const used = systemStatus.memory?.used ?? 0
  const total = systemStatus.memory?.total ?? 0
  return `${formatMemory(used)} / ${formatMemory(total)}`
})
const memoryPercentage = computed(() => Number(systemStatus.memory?.percentage ?? 0))

const mqttStatusColor = computed(() => (systemStatus.mqtt.connected ? '#52c41a' : '#ff4d4f'))
const mqttStatusText = computed(() => (systemStatus.mqtt.connected ? '已连接' : '未连接'))
const mqttSuccessRate = computed(() => {
  const sent = Number(systemStatus.mqtt.messagesSent || 0)
  const failed = Number(systemStatus.mqtt.messagesFailed || 0)
  const total = sent + failed
  return total > 0 ? (sent / total) * 100 : 0
})

const dataPointRows = computed(() => {
  if (!Array.isArray(systemStatus.dataPoints)) return []
  const rows = systemStatus.dataPoints.map((item) => ({
    deviceId: item.deviceId || '未命名',
    category: item.category || 'unknown',
    key: item.key || '--',
    value: item.value ?? null,
    unit: item.unit ?? '',
    timestamp: item.timestamp ?? null
  }))
  return rows.sort((a, b) => {
    if (a.deviceId !== b.deviceId) return a.deviceId.localeCompare(b.deviceId)
    if (a.category !== b.category) return a.category.localeCompare(b.category)
    if (a.key !== b.key) return a.key.localeCompare(b.key)
    return (a.timestamp || 0) - (b.timestamp || 0)
  })
})

// 方法
const getSuccessRateClass = (rate) => {
  if (rate >= 95) return 'text-success'
  if (rate >= 85) return 'text-warning'
  return 'text-danger'
}

const getSuccessRateColor = (rate) => {
  if (rate >= 95) return '#52c41a'
  if (rate >= 85) return '#faad14'
  return '#ff4d4f'
}

const getCpuColor = (usage) => {
  if (usage < 50) return '#52c41a'
  if (usage < 80) return '#faad14'
  return '#ff4d4f'
}

const getMemoryColor = (percentage) => {
  if (percentage < 60) return '#52c41a'
  if (percentage < 85) return '#faad14'
  return '#ff4d4f'
}

const formatPointValue = (value, unit) => {
  if (value === null || value === undefined) return '--'
  const numeric = Number(value)
  const formatted = Number.isNaN(numeric)
    ? value
    : numeric.toLocaleString(undefined, { maximumFractionDigits: 3 })
  return unit ? `${formatted} ${unit}` : formatted
}

const categoryTagType = (category) => {
  const lower = (category || '').toLowerCase()
  if (lower.includes('pcs')) return 'success'
  if (lower.includes('bms')) return 'warning'
  if (lower.includes('alarm')) return 'danger'
  return 'info'
}

// 刷新方法
// 生命周期
onMounted(() => {
  connectWebSocket()
  // 初始加载系统状态
  systemAPI.getStatus().catch(error => {
    console.error('获取初始系统状态失败:', error)
  })
})

onUnmounted(() => {
  disconnectWebSocket()
})
</script>

<style scoped>


.status-cards .stat-card {
  background: linear-gradient(135deg, #ffffff 0%, #f5f8ff 100%);
  border-radius: 14px;
  padding: 24px;
  box-shadow: 0 12px 28px rgba(41, 72, 152, 0.12);
  border: 1px solid rgba(255, 255, 255, 0.6);
  height: 150px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.status-cards .stat-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 16px 34px rgba(41, 72, 152, 0.18);
}

.stat-icon {
  margin-right: 18px;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 26px;
  font-weight: bold;
  color: #1f2d3d;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
  margin-bottom: 8px;
}

.stat-change {
  font-size: 12px;
}

.stat-change.positive {
  color: #52c41a;
}

.stat-change.negative {
  color: #ff4d4f;
}

.stat-extra {
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.stat-extra-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
  font-size: 12px;
}

.stat-extra-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.extra-label {
  color: #8c8c8c;
}

.extra-value {
  font-weight: 600;
  color: #1f2d3d;
}

.extra-danger {
  color: #ff4d4f;
}

.extra-success {
  font-size: 12px;
}

.stat-extra-progress {
  width: 100%;
  margin: 0;
}

.status-card {
  margin-bottom: 20px;
  border-radius: 16px;
  border: none;
  box-shadow: 0 10px 26px rgba(15, 42, 103, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.card-header .el-button {
  margin-left: auto;
}

.header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 12px;
}

.data-table-card {
  border-radius: 18px;
  overflow: hidden;
}

.data-points-table {
  --el-table-border-color: transparent;
}

.data-points-table :deep(.el-table__inner-wrapper::before) {
  display: none;
}

.data-points-table :deep(.el-table__body tr:hover > td) {
  background-color: rgba(66, 133, 244, 0.08);
}

.category-tag {
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.value-highlight {
  font-weight: 600;
  color: #1f2d3d;
}

.timestamp-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #60708a;
  font-size: 13px;
}

.stat-footnote {
  margin-top: 8px;
  font-size: 12px;
  color: #8c8c8c;
}

.websocket-status {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 8px;
  box-shadow: 0 8px 20px rgba(31, 76, 140, 0.12);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 16px;
  }

  .status-cards .stat-card {
    height: auto;
    padding: 16px;
    flex-direction: column;
    text-align: center;
  }
  
  .stat-icon {
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  .websocket-status {
    position: relative;
    bottom: auto;
    right: auto;
    margin-top: 20px;
    max-width: none;
  }

  .dashboard-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
